//3.3 /lib/code2/main_data35.dart
//bottomNavigationBar配制底部导航栏菜单
import 'dart:async';
import 'dart:convert';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_learn_vi/src/bean/bean_global.dart';
import 'package:flutter_learn_vi/src/common/global.dart';
import 'package:flutter_learn_vi/src/common/user_helper.dart';
import 'package:flutter_learn_vi/src/page/bloc/bloc_select_page.dart';
import 'package:flutter_learn_vi/src/page/common/app_upgrade.dart';
import 'package:flutter_learn_vi/src/page/common/common_dialog.dart';
import 'package:flutter_learn_vi/src/page/home/new/v4_custom_bottom_appbar.dart';
import 'package:flutter_learn_vi/src/page/home/new/v4_home_item_page.dart';
import 'package:flutter_learn_vi/src/page/login/bubble_login_page.dart';
import 'package:flutter_learn_vi/src/page/mine/new/v2_mine_main_page.dart';
import 'package:flutter_learn_vi/src/page/mine/question_model.dart';
import 'package:flutter_learn_vi/src/page/news/news_detaile_page.dart';
import 'package:flutter_learn_vi/src/page/study/main_study_page.dart';
import 'package:flutter_learn_vi/src/utils/log_util.dart';
import 'package:flutter_learn_vi/src/utils/navigator_utils.dart';
import 'package:flutter_learn_vi/src/utils/toast_utils.dart';

//lib/src/page/home/home_main_page.dart
//主页面的根布局
class HomeMainV4Page extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return _HomeMainState();
  }
}

class _HomeMainState extends State<HomeMainV4Page> with MineQuestionModel {
  //当前显示页面的标签
  int _tabIndex = 0;

  //[PageView]使用的控制器
  PageController _pageController = PageController();

  //底部导航栏使用到的图标
  List<Icon> _normalIcon;
  List<BottomNavigationBarItem> _bottomlist;
  List<Widget> _normalHomeBody;

  //底部导航栏使用到的标题文字
  List<String> _normalTitle;

  StreamSubscription _homeSubscription;

  @override
  void initState() {
    super.initState();
    _homeSubscription =
        rootStreamController.stream.listen(streamListenFunction);

    initHomeData();
    getQuestion();
    getStartPic();

    Future.delayed(Duration.zero, () {
      checkAppVersion(context);
    });
  }

  Widget buildRight() {
    //集团权限
    if (UserHelper.getInstance.userBean.userBlocType == 1) {
      return Container(
        child: InkWell(
          onTap: () {
            NavigatorUtils.pushPage(
                context,
                BlocSelectPage(
                  isShowAppBar: true,
                ));
          },
          child: Container(
            alignment: Alignment.center,
            padding: EdgeInsets.only(right: 8),
            child: Text(
              "切换",
              textAlign: TextAlign.center,
              style: TextStyle(
                fontWeight: FontWeight.w500,
                color: Colors.blue,
              ),
            ),
            // child: Image.asset(
            //   "assets/images/2.0x/keixingjituan.jpeg",
            //   width: 44,
            // ),
          ),
        ),
      );
    } else {
      return Container();
    }
  }

  void streamListenFunction(GlobalBean globalBean) {
    //刷新消息
    LogUtils.e("消息传递 刷新消息 ${globalBean.data.toString()}");
    if (globalBean.code == 202) {
      //清除缓存用户信息
      UserHelper.getInstance.exitLogin();
      //跳转登录页面
      NavigatorUtils.openPageByFade(
        context,
        BobbleLoginPage(),
        mills: 1000,
        endMills: 800,
        isReplace: true,
      );
    } else if (globalBean.code == 203) {
      getQuestion();
      getStartPic();
    }
  }

  initHomeData() {
    checkPassData();
  }

  void checkPassData() {
    _normalTitle = [
      "首页",
      "我的学习",
      "个人中心",
    ];
    _normalIcon = [
      Icon(Icons.home),
      Icon(Icons.import_contacts_sharp),
      Icon(Icons.people)
    ];

    _normalHomeBody = <Widget>[
      //第一个页面
      HomeItemMainV4Page(),
      MainStudyPage(),
      //个人中心
      MineMainV2Page(),
    ];

    _bottomlist = <BottomNavigationBarItem>[
      new BottomNavigationBarItem(label: _normalTitle[0], icon: _normalIcon[0]),
      new BottomNavigationBarItem(icon: _normalIcon[1], label: _normalTitle[1]),
      new BottomNavigationBarItem(icon: _normalIcon[2], label: _normalTitle[2]),
    ];
  }

  @override
  void dispose() {
    super.dispose();
    //移除监听
    _homeSubscription.cancel();
  }

  @override
  Widget build(BuildContext context) {
    //Scaffold 用来搭建页面的主体结构
    LogUtils.e("当前页面 $_tabIndex");
    //设置状态栏的颜色 有AppBar时，会被覆盖
    return AnnotatedRegion<SystemUiOverlayStyle>(
      child: Scaffold(
        backgroundColor: Colors.white,
        body: buildScaffold(),
      ),
      value: SystemUiOverlayStyle(
        //有Appbar时，会被覆盖
        statusBarIconBrightness: Brightness.dark,
      ),
    );
  }

  Scaffold buildScaffold() {
    return Scaffold(
      backgroundColor: Colors.white,
      //页面的主内容区
      //可以是单独的StatefulWidget 也可以是当前页面构建的如Text文本组件
      body: PageView(
        //设置PageView不可滑动切换
        physics: NeverScrollableScrollPhysics(),
        //PageView的控制器
        controller: _pageController,
        //PageView中的三个子页面
        children: _normalHomeBody,
      ),
      //底部导航栏
      bottomNavigationBar: BottomAppBar(
        //背景颜色
        color: Colors.white,
        //自定义底部菜单栏
        child: CustomBottomAppBarV4(
          clickCallBack: (int index) {
            _pageController.jumpToPage(index);
            LogUtils.e("切换PageView中的页面显示 $index");
            _tabIndex = index;
            setState(() {});
          },
        ),
      ),
    );
  }

  //lib/src/page/home/home_main_page.dart
  //构建底部导航栏
  BottomNavigationBar buildBottomNavigation() {
    //创建一个 BottomNavigationBar
    return new BottomNavigationBar(
      selectedItemColor: Colors.red,
      unselectedItemColor: Colors.grey,
      items: _bottomlist,
      //显示效果
      type: BottomNavigationBarType.fixed,
      //当前选中的页面
      currentIndex: _tabIndex,
      //图标的大小
      iconSize: 24.0,
      //点击事件
      onTap: (index) {
        //切换PageView中的页面显示
        LogUtils.e("切换PageView中的页面显示 $index");
        _pageController.jumpToPage(index);
        _tabIndex = index;
        setState(() {});
      },
    );
  }

  Widget buildHeader() {
    if (UserHelper.getInstance.mineBean == null) {
      return Container();
    }
    return Text(
      UserHelper.getInstance.mineBean.name,
      textAlign: TextAlign.center,
      style: TextStyle(
        fontSize: 18,
        fontWeight: FontWeight.w500,
        color: Colors.blueGrey,
      ),
    );
  }

  Widget buildHeaderImage() {
    if (UserHelper.getInstance.mineBean == null) {
      return Image.asset(
        "assets/images/3.0x/bg_header.png",
        fit: BoxFit.fill,
        width: 33,
        height: 33,
      );
    }
    String url = UserHelper.getInstance.mineBean.logoUrl;

    if (url == null || url.length == 0) {
      Image.asset(
        "assets/images/3.0x/bg_header.png",
        fit: BoxFit.fill,
        width: 33,
        height: 33,
      );
    }
    return Stack(
      alignment: Alignment.center,
      children: [
        Material(
          color: Colors.transparent,
          child: ClipOval(
            child: CachedNetworkImage(
              imageUrl: url,
              fit: BoxFit.fill,
              width: 33,
              height: 33,
            ),
          ),
        )
      ],
    );
  }



  void messageController(Map<String, dynamic> message) {
    String title = message["alert"];
    var extras = message["extras"];
    var pushModel = extras["cn.jpush.android.EXTRA"];
    try {
      if (pushModel != null) {
        final map = jsonDecode(pushModel);
        String pushModelString = map["pushModel"];
        final map2 = jsonDecode(pushModelString);
        final url = map2["url"];
        final newsId = map2["newsId"];
        showCommonAlertDialog(
            context: context,
            contentMessag: title,
            selectText: "去查看",
            cancleText: "不感兴趣",
            selectCallBack: () {
              if (newsId == null) {
                ToastUtils.showToast("暂无详情查看");
                return;
              }
              NavigatorUtils.pushPage(
                context,
                NewsDetailePage(
                  newsId: newsId,
                  screenSize: MediaQuery.of(context).size,
                ),
              );
            });
      }
    } catch (e) {
      LogUtils.e("极光推送消息解析失败");
    }
  }
}
